using UnityEngine;
using QFramework;
using UnityEditor;
using System.Collections;

namespace QFramework.FlappyBird
{
	public partial class Player : ViewController
	{
		private Rigidbody2D mrigidbody2D;
		private SpriteRenderer mspriteRenderer;
		private float jumpSpeed = 8;
		private bool mcheckScreen = false;

		IEnumerator Start()
		{
			// Code Here
			mrigidbody2D = GetComponent<Rigidbody2D>();

			mspriteRenderer = GetComponent<SpriteRenderer>();

			yield return new WaitForEndOfFrame();

			mcheckScreen = true;

			FlappyBird.GameState.RegisterWithInitValue(state =>
			{
				if (state == GameStates.NotStart)
				{
					mrigidbody2D.bodyType = RigidbodyType2D.Static;
				}
				else
				{
					mrigidbody2D.bodyType = RigidbodyType2D.Dynamic;
				}
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
		}

        private void Update()
        {
            if(Input.GetMouseButtonDown(0))
			{	
				if(FlappyBird.GameState.Value == GameStates.NotStart)
				{
					FlappyBird.GameState.Value = GameStates.Started;

                }
				if(FlappyBird.GameState.Value == GameStates.Started)
				{
                    mrigidbody2D.velocity = Vector2.up * jumpSpeed;
					AudioKit.PlaySound("JUMP");
                }
			}
			
			if(mrigidbody2D.velocity.y > 0)
			{
				var angleZ = Mathf.Lerp(0, 30, mrigidbody2D.velocity.y / 8);
				transform.localEulerAngles = new Vector3(0, 0, angleZ);
			}
			else
			{
                var angleZ = Mathf.Lerp(0, -30, Mathf.Abs(mrigidbody2D.velocity.y / 8));
                transform.localEulerAngles = new Vector3(0, 0, angleZ);
            }

			if(!mspriteRenderer.isVisible && mcheckScreen)
			{
                GameOver();
            }
        }

        private void OnCollisionEnter2D(Collision2D collision)
        {
			GameOver();
        }

        private void GameOver()
		{
			if(FlappyBird.GameState.Value == GameStates.Started)
			{
				FlappyBird.GameState.Value = GameStates.GameOver;
				AudioKit.PlaySound("DIE");
            }
		}
    }
}
